#include "utils.h"

void clean_stdin() {
    stdin->_IO_read_ptr = stdin->_IO_read_end;
}

char *get_str(char* str, size_t length) {
    if (str == NULL) {
        return NULL;
    }

    char * in = fgets(str, length, stdin);
    size_t cnt = strlen(str);
    if (str[cnt - 1] == '\n') {
        str[cnt - 1] = '\0';
    }
    clean_stdin();

    return str;
}

char get_sex() {
    printf("男M/女W");
    while(true) {
        char sex = getch();
        if (sex == 'W' || sex == 'M') {
            printf("性别是：%s", sex == 'W' ? "女":"男");
            return sex;
        }
    }
}

char* get_pwd(char* passwd, bool show, size_t length) {
    if (passwd == NULL) {
        return NULL;
    }

    int count = 0;
    do {
        char val = getch();
        if (val == 127) {
            if (count > 0) {
                if (show) printf("\b");
                count--;
            }
            continue;
        } else if (val == 10) {
            break;
        }
        passwd[count++] = val;
        if (show) printf("*");
    } while(count < length - 1);
    passwd[count] = '\0';
    return passwd;
}

int get_cmd(char start, char end) {
    clean_stdin();
    printf("请输入指令：");
    while (true)
    {
        char c = getch();
        if (c >= start && c <= end) {
            return c;
        }
    }
}
